package com.sunnada.edu.timer.controller;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;

import com.sunnada.edu.system.pub.common.AppContext;
import com.sunnada.edu.system.pub.common.LogInfo;
import com.sunnada.edu.system.pub.dao.PubDao;
import com.sunnada.edu.timer.service.StatisticsCrdThread;

/**
 * explain  考勤
 * @author  WJQ 2016-08-13
 * version 1.0
 */
@Controller
@Component 
public class StatisticsCrdTimer {
	/*@Scheduled(cron="0/5 * *  * * ? ")*/
	//@Scheduled(cron="0 0 23 * * ? ")
//	@Scheduled(cron="0 0/30 0/1 * * ? ")
//	@Scheduled(cron="0/20 * * * * ? ")
	//@Scheduled(cron="0 0 1 * * ? ")
	public  void  StatisticsCrd(){
		List<HashMap<String, String>> cList =(List<HashMap<String, String>>) findSchoolId();
		String todayData = getTodayData();
		String weekDay = getWeek(todayData);
		boolean isWeekend = isWeekend(todayData);
		HashMap<String, String> isMap = new HashMap<String, String>();
		for(HashMap<String, String> cmap:cList){
			String schoolId = cmap.get("SCHOOL_ID");
			String schoolName = cmap.get("SCHOOL_NAME");
			HashMap<String, String> map = new HashMap<String, String>();
			map.put("action", "考勤统计 "+todayData);
			map.put("loginSchoolId", schoolId);
			map.put("loginSchoolName", schoolName);
			map.put("loginUserId", "sys");
			map.put("loginUserName", "系统");
			isMap = getAttendanceState(schoolId,todayData,isWeekend);//今天是否需要统计
			boolean isWork = Boolean.parseBoolean(isMap.get("isWork"));
			boolean isMakeUp = Boolean.parseBoolean(isMap.get("isMakeUp"));
			if(isWork){
				map.put("result","统计");
				System.out.println(schoolId+" "+schoolName+" "+todayData+" "+weekDay+" 统计"+" 补课？"+isMakeUp);
				PubDao dao=AppContext.getInstance().getPubDao();
				String dSql = "delete from T_CRD_STATISTICS where person_id "
//						+ "in (select card_id from T_Student where School_Id = '"+schoolId+"' and rec_status<>'2' and CARD_ID is not null "
//						+ "union select card_id from T_TEACHER where School_Id = '"+schoolId+"' and rec_status<>'2' and CARD_ID is not null) "
//						+ "and person_id "
						+ "in (select student_id p_id from T_Student where School_Id = '"+schoolId+"' and rec_status<>'2' and CARD_ID is not null "
						+ "union select teacher_id p_id from T_TEACHER where School_Id = '"+schoolId+"' and rec_status<>'2' and CARD_ID is not null) "
						+ "and CRD_DATE = '"+todayData+"' and STATE not in ('31','32','33','34')";
				dao.delete(dSql);
				
				List<HashMap<String, String>> sList =(List<HashMap<String, String>>) getStudent(schoolId);//学生list
				System.out.println("学生："+sList.toString());
				new Thread(new StatisticsCrdThread(sList,todayData,weekDay,"1",isMakeUp,schoolId)).start();  
				List<HashMap<String, String>> tList =(List<HashMap<String, String>>) getTeacher(schoolId);//教师list
				System.out.println("教师："+tList.toString());
				new Thread(new StatisticsCrdThread(tList,todayData,weekDay,"0",isMakeUp,schoolId)).start();  
			}else{
				map.put("result","不上课");
				System.out.println(schoolId+" "+schoolName+" "+todayData+" "+weekDay+" 不统计"+" 补课？"+isMakeUp);
				PubDao dao=AppContext.getInstance().getPubDao();
				String dSql = "delete from T_CRD_STATISTICS where person_id "
						+ "in (select student_id p_id from T_Student where School_Id = '"+schoolId+"' and rec_status<>'2' and CARD_ID is not null "
						+ "union select teacher_id p_id from T_TEACHER where School_Id = '"+schoolId+"' and rec_status<>'2' and CARD_ID is not null) "
						+ "and CRD_DATE = '"+todayData+"' and STATE not in ('31','32','33','34')";
				dao.delete(dSql);
			}
			LogInfo.getInstance().option(map);
		}
		clear();
	}
	
	public List<?> findSchoolId(){
		PubDao dao=AppContext.getInstance().getPubDao();
        return dao.selectList(
        "select * from T_SCHOOL t where t.REC_STATUS <> '2' order by t.rec_id desc");
	}
	public List<?> getStudent(String schoolId){
		PubDao dao=AppContext.getInstance().getPubDao();
        return dao.selectList(
        "select distinct t.student_id p_id,t.card_id from T_Student t where t.School_Id = '"+schoolId+"' and t.rec_status<>'2' and t.CARD_ID is not null order by t.card_id desc");
	}
	public List<?> getTeacher(String schoolId){
		PubDao dao=AppContext.getInstance().getPubDao();
        return dao.selectList(
        "select distinct t.teacher_id p_id,t.card_id from T_TEACHER t where t.School_Id = '"+schoolId+"' and t.rec_status<>'2' and t.CARD_ID is not null order by t.card_id desc");
	}
	public HashMap<String, String> getAttendanceState(String schoolId,String todayData,boolean isWeekend){
		HashMap<String, String> isMap = new HashMap<String, String>();
		String isWork = "true";
		String isMakeUp = "false";
		PubDao dao=AppContext.getInstance().getPubDao();
		String lsql= "select t.TIMETYPE from T_ATTENDANCEDATESET t where t.school_id='"+schoolId+"' "
		+"and t.rec_status<>'2' "
		+"and to_date(t.BEGIN_TIME,'yyyy-mm-dd') <= to_date('"+todayData+"','yyyy-mm-dd') "
		+"and to_date(t.END_TIME,'yyyy-mm-dd') >= to_date('"+todayData+"','yyyy-mm-dd') "
		;
		System.out.println(lsql);
		List<?> aList =  dao.selectList(lsql);
		int aInt = aList.size();
		if(aInt>0){
			HashMap<String, String> rmap = (HashMap<String, String>) aList.get(0);
			String TIMETYPE = rmap.get("TIMETYPE");
			if("1".equals(TIMETYPE)){
				isWork="false";
			}else if("2".equals(TIMETYPE)){
				isWork="false";
			}else if("3".equals(TIMETYPE)){
				isWork="true";
				isMakeUp="true";
			}else if("4".equals(TIMETYPE)){
				isWork="true";
				isMakeUp="true";
			}
		}
		isMap.put("isWork", isWork);
		isMap.put("isMakeUp", isMakeUp);
		return isMap;
		
	}
	//获取前一天日期
	public String getTodayData(){
		Date dNow = new Date();   //当前时间
		Date dBefore = new Date();

		Calendar calendar = Calendar.getInstance(); //得到日历
		calendar.setTime(dNow);//把当前时间赋给日历
		calendar.add(Calendar.DAY_OF_MONTH, -1);  //设置为前一天
		dBefore = calendar.getTime();   //得到前一天的时间

		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd"); //设置时间格式
		String defaultStartDate = sdf.format(dBefore); 
		return defaultStartDate;
	}
	public String getWeek(String s){
		String dayNames[] = { "周日", "周一", "周二", "周三", "周四", "周五", "周六" };
		SimpleDateFormat sdfInput = new SimpleDateFormat("yyyy-MM-dd");
		Calendar calendar = Calendar.getInstance();
		Date date = new Date();
		try {
			date = sdfInput.parse(s);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		calendar.setTime(date);
		int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK)-1;
		if(dayOfWeek<0)dayOfWeek=0;
		
		System.out.println(dayNames[dayOfWeek]);
		
		return dayNames[dayOfWeek];
	}
	private boolean isWeekend(String todayData){  
		DateFormat format = new SimpleDateFormat("yyyy-MM-dd");        
		Date bdate = null;
		try {
			bdate = format.parse(todayData);
		} catch (ParseException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		} 
		Calendar cal = Calendar.getInstance();
		cal.setTime(bdate);
		if(cal.get(Calendar.DAY_OF_WEEK)==Calendar.SATURDAY||cal.get(Calendar.DAY_OF_WEEK)==Calendar.SUNDAY){
		  return true;
		}else{
		    return false;
		}
	} 
	public static void main(String[] args) {
		StatisticsCrdTimer timer =new StatisticsCrdTimer();
		System.out.println(timer.getAttendanceState("1","2016-08-11",true));
	}
	public void clear() {
		System.gc();
	}
}
